import axios from 'axios'
import { router } from '../router/index'
import { useUserStore } from '../store/user/index'
import { ElMessage } from "element-plus";
const instance = axios.create({
    baseURL: 'http://xue.cnkdl.cn:9082/mall-admin/',
})

// 拦截器
instance.interceptors.request.use(config => {
    let token = localStorage.getItem('token')
    if (token) {
        config.headers && (config.headers['Authorization'] = token)
    }

    return config
}, err => Promise.reject(err))



instance.interceptors.response.use(res => {
    const store = useUserStore()
    if (res.data.code == 401) {
        // 回到登录
        router.push('/login')
        // 清除token
        localStorage.removeItem("token")
        // 清除动态路由
        store.activeMenus.forEach((item) => {
            router.removeRoute(item.name)
        })
        // 清除动态路由
        router.removeRoute('home')
        // 清空数组
        store.menus = [];

    }

    return res.data
}, err => {
    ElMessage.error("出现错误，请联系管理员");
    return Promise.reject(err)
})

export default instance